package io.gitee.zicai.nacos.consumer.controller

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate

/**
 * ConsumerController
 *
 * @author zicai
 * @since 2019-01-17
 */
@RestController
@RequestMapping("/t")
open class ConsumerController {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    @Autowired
    private lateinit var loadBalancerClient: LoadBalancerClient

    @GetMapping("/hello/{name}")
    open fun hello(@PathVariable("name") name: String?) : String? {
//        getRest(name)
        return getProvider(name)
    }

    private fun getProvider(name: String?): String? {
        val service = loadBalancerClient.choose("zicai-nacos-provider")
        val url = "${service.uri}/t/hello/$name".also { println(it) }
        return RestTemplate().getForObject(url, String::class.java).also { println("loadBalancer -> $it") }
    }

    private fun getRest(name: String?): String? {
        return restTemplate.getForObject("http://zicai-nacos-provider/t/hello/$name", String::class.java).also { println("restTemplate -> $it") }
    }
}